package simtools.xml.convert;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class Routers {

	public static List<Map<String, String>> parse(InputStream src) throws IOException {

		// The document as published by the OMB is encoded in Latin-1
		InputStreamReader isr = new InputStreamReader(src, "8859_1");
		BufferedReader in = new BufferedReader(isr);
		List<Map<String, String>> records = new ArrayList<Map<String, String>>();
		String lineItem;
		while ((lineItem = in.readLine()) != null) {
			records.add(splitLine(lineItem));
		}
		return records;
	}

	// the field names in order
	public final static String[] keys = { "NodeFrom", "NodeTo", "LinkSpeed", "Delay", "Queue" };

	private static Map<String, String> splitLine(String record) {

		record = record.trim();

		int index = 0;
		Map<String, String> result = new HashMap<String, String>();
		for (int i = 0; i < keys.length; i++) {

			StringBuffer sb = new StringBuffer();
			char c;
			while (index < record.length()) {
				c = record.charAt(index);

				if (c == ' ')
					break;
				else
					sb.append(c);

				index++;
				if (index == record.length())
					break;
			}

			String s = sb.toString().trim();
			if (s.equals("") )
				s = "null";
			result.put(keys[i], s);
			index++;
		}

		return result;
	}

	public static void convert(List<Map<String, String>> data, OutputStream out) throws IOException {

		Writer wout = new OutputStreamWriter(out, "UTF8");
		wout.write("<?xml version=\"1.0\"?>\r\n");
		wout.write("<!DOCTYPE Links SYSTEM \"Routers.dtd\">\r\n");
		wout.write("<Links>\r\n");

		Iterator<Map<String, String>> records = data.iterator();
		while (records.hasNext()) {
			wout.write("  <Link>\r\n");
			Map<String, String> record = records.next();
			Set<Entry<String, String>> fields = record.entrySet();
			Iterator<Entry<String, String>> entries = fields.iterator();
			while (entries.hasNext()) {
				Entry<String, String> entry = entries.next();
				String name = entry.getKey();
				String value = entry.getValue();

				wout.write("    <" + name + ">");
				wout.write(value);
				wout.write("</" + name + ">\r\n");
			}
			wout.write("  </Link>\r\n");
		}
		wout.write("</Links>\r\n");
		wout.flush();

	}

	public static void main(String[] args) {

		try {
			InputStream in = new FileInputStream(
					"xml/scenario4/as3037");
			OutputStream out;
			out = new FileOutputStream(
					"xml/scenario4/Routers.xml");

			List<Map<String, String>> results = parse(in);
			convert(results, out);
		} catch (IOException e) {
			System.err.println(e);
		}
	}
}
